/* Filename: abcd_cond.c
 * $ ps axm
 * $ ps ax -L
 * Description:
 * $ gcc -Wall abcd_cond.c -o abcd_cond -lpthread
 * Last modified: humble 20200416 22:17
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define THRNUM (4)

static pthread_mutex_t mut[THRNUM];

static void usage(void);

static int next(int n)
{
    if(n + 1 == THRNUM){
        return 0;
    }
    return n + 1;
}


static void *thr_abcd(void *p)
{
    int n = (int)p;
    int c = 'a' + (int)p;

    while(1){
        pthread_mutex_lock(mut + n);
        write(1, &c, 1);
        pthread_mutex_unlock(mut + next(n));
    }

    pthread_exit(NULL);
}

int main(int argc, char **argv)
{
    int i, err;
    pthread_t tid[THRNUM];

    if(argc != 1){
        fprintf(stderr, "argc !=1");
        usage();
        exit(1);
    }

    for(i = 0; i < THRNUM; i++)
    {
        pthread_mutex_init(mut + i, NULL);
        pthread_mutex_lock(mut + i);
        err = pthread_create(tid + i, NULL, thr_abcd, (void *)i);
        if(err){
            fprintf(stderr, "pthread_create():%s\n", strerror(err));
            exit(1);
        }
    }

    pthread_mutex_unlock(mut + 0);

    alarm(5);

    for(i = 0; i < THRNUM; i++)
    {
        pthread_join(tid[i], NULL);
    }

    return 0;
}

static void usage(void)
{
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
